#include "configmanager.h"
#include <QSettings>
#include <QGuiApplication>
#include <QCursor>

QAtomicPointer<ConfigManager> ConfigManager::m_instance(nullptr);
QMutex ConfigManager::mutex;

ConfigManager* ConfigManager::getInstance()
{
    ConfigManager* tmp = m_instance.loadAcquire();
    if (!tmp) {
        QMutexLocker locker(&mutex);
        tmp = m_instance.loadAcquire();
        if (!tmp) {
            tmp = new ConfigManager();
            m_instance.storeRelease(tmp);
        }
    }
    return tmp;
}

void ConfigManager::setFile(const QString &configFile)
{
    m_configFile = configFile;
}

SerialConfig ConfigManager::load()
{
    if (m_configFile.isEmpty()) {
            throw ConfigManagerException("Failed to load configuration", "Config file path is empty.");
        }

        QSettings set(m_configFile, QSettings::IniFormat);
        if (set.status() != QSettings::NoError) {
            throw ConfigManagerException("Failed to load configuration", "Unable to open the config file.");
        }

        SerialConfig config;
        set.beginGroup("Serial");
        config.portName = set.value("PortName").toString();
        config.baudRate = set.value("BaudRate").toInt();
        config.dataBits = set.value("DataBits").toInt();
        config.parity = set.value("Parity").toInt();
        config.stopBits = set.value("StopBits").toInt();
        config.flowControl = set.value("FlowControl").toString();
        set.endGroup();
        m_currentConfig = config;  // 保存当前配置
        return config;
}

bool ConfigManager::saveAs(const QString &fileName)
{
    if (m_configFile != fileName) {
        m_configFile = fileName;
    }
    return save();
}

bool ConfigManager::save()
{
    if (m_configFile.isEmpty()) {
            throw ConfigManagerException("Failed to save configuration", "Config file path is empty.");
        }

        QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
        QSettings settings(m_configFile, QSettings::IniFormat);

        settings.beginGroup("Serial");
        settings.setValue("PortName", m_currentConfig.portName);
        settings.setValue("BaudRate", m_currentConfig.baudRate);
        settings.setValue("DataBits", m_currentConfig.dataBits);
        settings.setValue("Parity", m_currentConfig.parity);
        settings.setValue("StopBits", m_currentConfig.stopBits);
        settings.setValue("FlowControl", m_currentConfig.flowControl);
        settings.endGroup();

        QGuiApplication::restoreOverrideCursor();
    return true;
}
